const {
  studentRegister,
  getPhoneNumber,
  getUserProfile,
  educationalExperience,
  requestSubscribeMessage
} = require('../../../../api/index');
const {
  getDict,
  getBatchDict
} = require('../../../../utils/dict');
const WXBizDataCrypt = require('../../../../utils/WXBizDataCrypt');

const {
  validate,
  getSex
} = require('../../../../utils/util');

const {
  education_access
} = require('../../../../utils/config');

// pages/authentication/index/index.js
Page({
  /*** 页面的初始数据 */
  data: {
    selectSchool: 'register1',
    genderDicts: [],
    formData: {
      student: {
        phone: "",
        realName: '',
        gender: "0",
        genderName: '',
        identityCard: '',
        highestEducation: '',
        avatar: "",
        openId: '',
        highSchool: '',
        workUnit: '', //  工作单位
        interest: '', // 兴趣爱好 
        strongPoint: '', // 特长
        otherRequirement: '', // 其他需求
      },
      educationalExperienceList: []
    },
    errors: {},
    rules: {
      gender: [{
        empty: true,
        msg: '性别不能为空'
      }],
      phone: [{
          empty: true,
          msg: '手机号不能为空'
        },
        {
          rule: val => /^1(3|4|5|6|7|8|9)\d{9}$/.test(val),
          msg: '手机号码格式有误'
        }
      ],
      highSchool: [{
        empty: true,
        msg: '高中学校不能为空'
      }],
      highestEducation: [{
        empty: true,
        msg: '最高学历不能为空'
      }]
    },
    rules2: {
      educationalExperienceList: [{
        empty: true,
        msg: '至少有一个教育经历'
      }]
    },
  },
  //  页面跳转
  onJump(event) {
    const {
      url
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url
    });
  },
  onDelete(event) { //  删除 - 删除元素
    const {
      index
    } = event.currentTarget.dataset;
    //  删掉指定元素
    this.data.formData.educationalExperienceList.splice(index, 1);
    //  更新 storage
    wx.setStorageSync('educationalExperienceList', this.data.formData.educationalExperienceList);
    //  注意 深层次的要进行 优化
    this.setData({
      formData: JSON.parse(JSON.stringify(this.data.formData))
    });
  },
  onEdit(event) { //  编辑
    const {
      index
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/packageA/pages/authentication/addExperience/index?index=${ index }`
    });
  },
  //  修改表单数据
  onFormData(event) {
    const {
      prop
    } = event.currentTarget.dataset;
    this.data.formData[prop] = event.detail;
  },
  onFormDataStudent(event) {
    const {
      prop
    } = event.currentTarget.dataset;
    this.data.formData.student[prop] = event.detail;
  },
  // 提交数据
  async onSubmit(event) {
    console.log(this.data.formData.student);
    //  判断返回的错误集合是否是空的，如果空则说明验证通过了，否则将错误显示到页面上
    const error = validate(this.data.formData.student, this.data.rules) || {};
    const error2 = validate({
      educationalExperienceList: this.data.formData.educationalExperienceList
    }, this.data.rules2) || {};
    const concatError = Object.assign({}, error, error2);

    this.setData({
      errors: concatError
    });


    if (JSON.stringify(concatError) !== '{}') { //  如果报错就不允许进行数据的提交
      return;
    }

    const {
      errors = [], token, id
    } = await studentRegister(this.data.formData);
    if (errors.length > 0) {
      return;
    }

    //  清空缓存，进入首页
    //  设置学子 id 证明已经注册过了
    wx.setStorageSync('studentid', id);
    wx.setStorageSync('token', token);

    //  授权成功 之后调整页面
    const res = await requestSubscribeMessage([education_access]);

    if (res[education_access] = "accept") {
      wx.showToast({
        title: '订阅成功',
        icon: 'success',
        duration: 1000,
        success() {
          //  提交成功 跳转到 成功页面
          const url = '/pages/home/index';
          wx.navigateTo({
            url: `/packageA/pages/success/index?type=archive_registr&url=${ url }`
          });
        }
      })

    } else { //  提示未通过
      //  提交成功 跳转到 成功页面
      const url = '/pages/home/index';
      wx.navigateTo({
        url: `/packageA/pages/success/index?type=archive_registr&url=${ url }`
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.showLoading({
      title: '加载中...'
    });
    await fetchDicts.call(this);
    initFormData.call(this);
    this.setData({
      formData: this.data.formData
    });
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.data.errors.educationalExperienceList = '';
    const educationalExperienceList = wx.getStorageSync('educationalExperienceList') || [];
    const collegeName = wx.getStorageSync(this.data.selectSchool)?.collegeName;
    this.data.formData.educationalExperienceList = educationalExperienceList;
    collegeName && (this.data.formData.student.highSchool = collegeName);

    this.setData({
      errors: JSON.parse(JSON.stringify(this.data.errors)),
      formData: JSON.parse(JSON.stringify(this.data.formData))
    });
  },
  /*** 生命周期函数--监听页面卸载 */
  onUnload() {
    //  卸载的时候清除掉缓存的数据
    wx.removeStorageSync('educationalExperienceList');
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

async function initFormData() {
  const avatarUrl = wx.getStorageSync('avatarUrl');
  const {
    username,
    idCard
  } = wx.getStorageSync('authentication');
  const gender = getSex(idCard);
  this.data.formData.student.gender = gender;
  this.data.formData.student.genderName = this.data.genderDicts.find(_s => _s.code == gender)?.name;
  this.data.formData.student.avatar = avatarUrl;
  this.data.formData.student.realName = username;
  this.data.formData.student.identityCard = idCard;
  this.data.formData.student.openId = wx.getStorageSync('openid');
  this.setData({
    formData: JSON.parse(JSON.stringify(this.data.formData))
  });
}

//  获取所需要的字典项
async function fetchDicts() {
  const [genderDicts] = await getBatchDict(['GENDER']);

  console.log(genderDicts);
  this.data.genderDicts = genderDicts;
}


//  处理表单数据
async function setFormData() {
  const _formData = JSON.parse(JSON.stringify(this.data.formData));
  return _formData;
}